<template>
  <yc-container spacious>
    <yc-search-panel slot="header" v-model="active">
      <yc-bar slot="title">
        <yc-bar-space />
        <yc-bar-cell>
          <yc-pagination :full="false" @change="handlePageChange" :pagination="pagination" />
        </yc-bar-cell>
        <yc-bar-space />
        <yc-bar-cell>
          <el-button-group>
            <yc-button size="mini" icon="el-icon-refresh" label="刷新" @click="handleFetchTableData" />
            <yc-button size="mini" icon="el-icon-set-up" label="设置" @click="handleSettingTable" />
          </el-button-group>
        </yc-bar-cell>
        <yc-bar-cell>
          <yc-button type="primary" size="mini" icon="el-icon-plus" label="新增" v-permission="['management:role:add']"
            @click="handleCreate" />
        </yc-bar-cell>
      </yc-bar>
      <yc-form ref='form' v-model="search" :setting="formSetting" :itemSetting="formItemSetting" />
    </yc-search-panel>
    <el-container>
      <el-aside>
        <yc-table height="100%" ref="table" :api="api" :paging="false" :columns="columns" :pagination="pagination"
          @current-change="handleCurrentChange" :checkbox-config="{checkMethod}" highlight-current-row>
          <template v-slot:moreOperation="{ row }">
            <yc-button type="text" size="mini" label="编辑" v-permission="['management:role:update']"
              @click="handleUpdate(row)" />
            <yc-button :disabled="isAdministrator(row)" size="mini" type="text" label="删除"
              v-permission="['management:role:delete']" @click="$refs.table.handleDeleteRow(row)" />
          </template>
          <template v-slot:switchOperation="{row}">
            <el-switch v-model="row.status" activeColor='#13ce66' inactiveColor='#ff4949' :activeValue='activeValue'
              :inactiveValue='inactiveValue' :disabled="isAdministrator(row)" @change="handleChangeStatus({row})">
            </el-switch>
          </template>
        </yc-table>
      </el-aside>
      <el-main>
        <yc-bar class="main-bar">
          <yc-bar-space />
          <yc-bar-cell>
            <yc-button type="primary" :disabled="isAdministrator(selectRow)" size="mini" label="保存"
              v-permission="['management:role:update']" @click="saveRoleMenuRelation" />
          </yc-bar-cell>
        </yc-bar>
        <el-scrollbar>
          <el-tree :data="treeData" show-checkbox node-key="id" ref="menuTree" @check-change="handleTreeCheckChange"
            v-loading="menuTreeLoading" :props="defaultProps">
          </el-tree>
        </el-scrollbar>
      </el-main>
    </el-container>
    <yc-bar slot="footer">
      <yc-bar-cell>
        <yc-button type="primary" size="mini" icon="el-icon-tickets" label="全选" @click="handleAllSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document-copy" label="反选" @click="handleInvertSelection" />
        <yc-button type="primary" size="mini" icon="el-icon-document" label="全不选" @click="handleAllNoneSelection" />
        <yc-button type="danger" size="mini" icon="el-icon-delete" label="删除" v-permission="['management:role:delete']"
          @click="handleDeleteTable" />
      </yc-bar-cell>
      <yc-bar-space />
      <yc-bar-cell>
        <!-- <vxe-pager
                        size="mini"
                        @page-change="handlePageChange"
                        :page-sizes="[25, 50, 100, 150]"
                        :current-page="pagination.current"
                        :page-size="pagination.size"
                        :total="pagination.total"
                        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']">
                  </vxe-pager> -->
      </yc-bar-cell>
    </yc-bar>
    <yc-dialog width="600px" :mode="mode" :conf="dialogConf" @on-submit="handleSubmit">
      <yc-form ref="roleForm" v-model="formData" :setting="roleFormSetting" :itemSetting="roleFormItemSetting" />
    </yc-dialog>
  </yc-container>
</template>

<script>

import { queryRoles, addRole, updateRole, removeRole } from '@api/management/role'
import { queryMenus } from '@/api/management/menu'
import { queryRoleMenuRelations, addRoleMenuRelation } from '@/api/management/role-menu-relation'
import XEUtils from 'xe-utils'
import util from '@/libs/util'
import crud from '@/mixins/crud'
export default {
  name: 'role',
  mixins: [crud],
  data () {
    return {
      api: {
        index: queryRoles,
        modify: updateRole,
        del: removeRole
      },
      mode: 'create',
      columns: [
        { key: 'checkbox', type: 'checkbox', width: '50', fixed: 'left' },
        { key: 'seq', type: 'seq', width: '50', fixed: 'left' },
        { key: 'name', field: 'name', title: '名称', minWidth: '150', formatter: 'formatEmpty', fixed: 'left' },
        { key: 'permission', field: 'permission', minWidth: '150', title: '权限标识', formatter: 'formatEmpty' },
        { key: 'remark', field: 'remark', minWidth: '150', title: '描述', formatter: 'formatEmpty' },
        { key: 'createTime', field: 'createTime', minWidth: '150', title: '创建日期' },
        { key: 'status', field: 'status', title: '状态', width: '120', fixed: 'right', slots: { default: 'switchOperation' } },
        { key: 'operation', title: '操作', width: '120', fixed: 'right', slots: { default: 'moreOperation' } }
      ],
      formSetting: {
        useLayout: false,
        inline: true,
        size: 'mini',
        labelPosition: 'top'
      },
      formItemSetting: [
        {
          prop: 'name',
          default: '',
          title: '名称',
          col: { span: 6 },
          name: 'input',
          clearable: true,
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 6 },
          name: 'dict-select',
          dictName: 'normal_status',
          visible: true
        },
        {
          title: '操作',
          visible: true,
          name: 'button-group',
          options: [
            {
              label: '搜索',
              type: 'primary',
              click: () => { this.handleFetchTableData() }
            },
            {
              label: '重置',
              click: () => { this.handleRestTableData() }
            }
          ]
        }
      ],
      dialogConf: {
        dialogVisible: false
      },
      formData: {},
      selectRow: null,
      treeData: [],
      cacheTreeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuTreeLoading: true,
      activeValue: 1,
      inactiveValue: 0
    }
  },
  computed: {
    roleFormSetting () {
      return {
        useLayout: true,
        inline: false,
        size: 'mini',
        labelPosition: 'right',
        labelWidth: '150px'
      }
    },
    roleFormItemSetting () {
      return [
        {
          prop: 'name',
          default: '',
          title: '角色名称',
          col: { span: 18 },
          name: 'input',
          rule: { required: true, message: '请输入角色名称', trigger: 'change' },
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'permission',
          default: '',
          title: '权限标识',
          col: { span: 18 },
          name: 'input',
          rule: { required: true, message: '请输入权限标识', trigger: 'change' },
          disabled: this.isAdministrator(this.formData),
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'remark',
          default: '',
          title: '描述',
          col: { span: 18 },
          name: 'input',
          visible: true,
          placeholder: '请输入内容'
        },
        {
          prop: 'status',
          default: 1,
          title: '状态',
          col: { span: 18 },
          disabled: this.isAdministrator(this.formData),
          name: 'dict-radio',
          dictName: 'normal_status',
          visible: true
        }
      ]
    }
  },
  created () {
    this.fetchMenuData()
  },
  mounted () {
  },
  methods: {
    fetchMenuData () {
      this.menuTreeLoading = true
      queryMenus().then(res => {
        this.treeData = util.treeData(res.data)
        this.cacheTreeData = util.treeData(res.data)
        this.menuTreeLoading = false
      })
    },
    handleCreate () {
      this.mode = 'create'
      this.formData = {}
      this.dialogConf.dialogVisible = true
    },
    handleUpdate (row) {
      this.mode = 'update'
      this.selectRow = row
      this.formData = this.$_.cloneDeep(row)
      this.dialogConf.dialogVisible = true
    },
    handleSubmit (callBack) {
      var record = this.formData
      if (this.mode === 'create') {
        addRole(record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('添加成功')
            this.$refs.table.insertRow(data, null, null)
          } else {
            this.$message.error('添加失败')
          }
          callBack(code === 200)
        })
      } else {
        updateRole(record.id, record).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.$message.success('修改成功')
            this.$refs.table.updateRow(this.selectRow, data)
            this.selectRow = null
          } else {
            this.$message.error('修改失败')
          }
          callBack(code === 200)
        })
      }
    },
    saveRoleMenuRelation () {
      if (!this.selectRow) {
        this.$message.warning('请选择行')
        return
      }
      var arr = this.$refs.menuTree.getCheckedNodes(true)
      var roleId = this.selectRow.id
      var params = {
        roleId: roleId
      }
      if (arr.length) {
        params.roleMenuRelationList = arr.map(e => { return { roleId: roleId, menuId: e.id } })
      }
      addRoleMenuRelation(params).then(res => {
        var { code } = res
        if (code === 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error('保存失败')
        }
      })
    },
    handleCurrentChange ({ row }) {
      this.selectRow = row
      var isAdmin = this.isAdministrator(row)
      if (isAdmin) {
        this.$refs.menuTree.setCheckedNodes(this.cacheTreeData)
        return
      }
      this.treeData = this.$_.cloneDeep(this.cacheTreeData)
      this.menuTreeLoading = true
      var params = {
        roleId: row.id
      }
      queryRoleMenuRelations(params).then(res => {
        var { code, data } = res
        if (code === 200) {
          var menuIds = data.map(e => { return e.menuId })
          this.$refs.menuTree.setCheckedKeys(menuIds)
        } else {
          this.$message.error('查询失败')
        }
        this.menuTreeLoading = false
      })
    },
    isAdministrator (row) {
      if (row === null) return false
      return row.permission === 'administrator'
    },
    handleTreeCheckChange (data, checked, indeterminate) {
      var isAdmin = this.isAdministrator(this.selectRow)
      if (isAdmin) {
        XEUtils.eachTree(this.treeData, e => {
          e.disabled = true
        })
      }
    },
    checkMethod ({ row }) {
      return !this.isAdministrator(row)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-container {
  width: 100%;
  height: 100%;
}
.el-aside {
  width: 80% !important;
  height: 100%;
}
.el-main {
  padding: 0px 5px !important;
  border: 1px solid #e8eaec;
  margin-left: 20px;
}
.main-bar {
  height: 35px;
  line-height: 36px;
  border-bottom: 1px solid #e8eaec;
  background-color: #f8f8f9;
}
.el-scrollbar {
  height: calc(100% - 48px);
  ::v-deep.el-scrollbar__wrap {
    overflow-x: hidden;
    margin-bottom: 0px !important;
    ::v-deep.el-scrollbar__view {
      height: 100%;
    }
  }
}
</style>
